package com.xopencode.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

/**
 * TCP服务-客户端
 * @Author mcb
 * @Version 1.0
 */
public class NettyClient {

    public void run() throws InterruptedException {
        EventLoopGroup group=new NioEventLoopGroup();
        //创建客户端的启动助手
        Bootstrap bootstrap=new Bootstrap();
        //开始配置
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());//字符串编码发送
                        //pipeline 管道
                        ch.pipeline().addLast(new NettyClientHandler());//具体业务处理
                    }
                });
        System.out.println("Client: 准备就绪！！！");
        //启动客户端去连接服务器
        ChannelFuture cf = bootstrap.connect("127.0.0.1", 8765).sync();
        ChannelFuture cf2 = bootstrap.connect("127.0.0.1", 8766).sync();

        cf.channel().closeFuture().sync();//等待关闭
        cf2.channel().closeFuture().sync();//等待关闭

        System.out.println("Client--关闭通道！！！");
        group.shutdownGracefully();
        System.out.println("Client--关闭线程组！！！");

    }

    public static void main(String[] args) {
        try {
            new NettyClient().run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
